package com.xcms.servlets;

import org.jspecial.tools.Combiner;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Collections;
import java.security.Principal;

/**
 * Servlet responsible for scripts combining.
 */
public class EditorScriptServlet extends HttpServlet
{
    private static final String SRC_DIR = "/scripts";
    private static final String LOADER_SCRIPT = "loader.js";

    private static final String[] CLASSES = new String[]{
            "xcms.Initializer"
    };

    private static final Map<String, String> DEFAULT_PLUGINS =
            Collections.singletonMap( "auth", "xcms.plugins.auth.AuthPlugin" );

    private static final Map<String, String> AUTHENTICATED_PLUGINS =
            Collections.singletonMap( "editor", "xcms.plugins.editor.EditorPlugin" );

    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        Writer out = response.getWriter();
        ServletContext context = getServletContext();
        File srcDir = new File( context.getRealPath( SRC_DIR ) );

        out.write( FileUtils.readFileToString( new File( srcDir, LOADER_SCRIPT ) ) );
        Combiner scriptCombiner = new Combiner( srcDir );
        for( String className : CLASSES )
        {
            scriptCombiner.addClass( className );
        }
        Map<String, String> plugins = isAuthenticated() ? AUTHENTICATED_PLUGINS : DEFAULT_PLUGINS;
        for( String pluginClass : plugins.values() )
        {
            scriptCombiner.addClass( pluginClass );
        }

        scriptCombiner.combine( out );
        out.write( getInitScript( null, plugins ) );
    }

    private boolean isAuthenticated()
    {
        // TODO: implement server-side authentication
        return false;
    }

    private String getInitScript( String userid, Map<String, String> plugins )
    {
        StringBuilder builder = new StringBuilder();
        builder.append( "xcms.init(" );
        JSONObject config = new JSONObject();
        config.put( "userid", userid ); 
        config.put( "plugins", new JSONObject( plugins ) );
        builder.append( config.toString() );
        builder.append( ")" );
        return builder.toString();
    }
}
